package com.significantfiles.snapshot.engine.io;

import java.io.File;
import java.io.IOException;

import org.jboss.marshalling.Marshaller;
import org.jboss.marshalling.MarshallingConfiguration;
import org.jboss.marshalling.river.RiverMarshallerFactory;

public class Snapshot {

	private final File snapshot;
	private final File backup;
	private final String snapshotName;

	private final MarshallingConfiguration configuration;
	private final RiverMarshallerFactory factory;
	private final int partNr;

	public Snapshot(final File dir, final int partNr) {
		if (dir == null)
			throw new NullPointerException();

		this.partNr = partNr;

		this.snapshotName = createSnapshotName();
		this.snapshot = createSnapshotFile(dir);
		this.backup = createBackupFile(dir);

		this.factory = new RiverMarshallerFactory();
		this.configuration = new MarshallingConfiguration();
		this.configuration.setBufferSize(4096);
	}

	public Marshaller createMarshaller() throws IOException {
		final Marshaller rval = factory.createMarshaller(configuration);

		final FileByteOutput out = new FileByteOutput( this.backup );
		rval.start(out);

		return rval;
	}

	private File createBackupFile(File dir) {
		final String name = this.snapshotName + ".sbf";
		return new File(dir, name);
	}

	private File createSnapshotFile(final File dir) {
		final String name = this.snapshotName + ".sdf";
		return new File(dir, name);
	}

	private String createSnapshotName() {
		return "snapshot"+ this.partNr;
	}

	public File getBackupFile() {
		return this.backup;
	}

}
